﻿using FreeSql;
using LF.Common;

namespace LF.Domain.Helper
{
    internal class FreeSqlHelper
    {
        static IFreeSql? _freeSql;

        public static IFreeSql DbContext
        {

            get
            {
                if (_freeSql == null)
                {
                    FreeSql.Internal.Utils.TypeHandlers.TryAdd(typeof(DateOnly), new StringDateOnly());
                    FreeSql.Internal.Utils.TypeHandlers.TryAdd(typeof(MonthOnly), new StringMonthOnly());

                    _freeSql = new FreeSqlBuilder()
                       .UseConnectionString(DataType.MySql, DomainConfig.Connection)
#if DEBUG
                       .UseAutoSyncStructure(true) //自动同步实体结构到数据库
#endif
                       .Build();
                    _freeSql.Aop.AuditValue += Aop_AuditValue;
                    _freeSql.Aop.CurdAfter += Aop_CurdAfter;
                    _freeSql.Aop.ConfigEntityProperty += Aop_ConfigEntityProperty;
                    //_freeSql.CodeFirst.ConfigEntity<WorkOrder>(e => {
                    //    e.Property(x => x.Status).MapType(typeof(string)); // 关键配置 
                    //});

#if DEBUG
                    _freeSql.Aop.CommandAfter += (s, e) =>
                    {
                        Console.WriteLine(e.Command.CommandText);
                    };
#endif
                }

                return _freeSql;
            }
        }

        private static void Aop_AuditValue(object? sender, FreeSql.Aop.AuditValueEventArgs e)
        {
            if (e.AuditValueType == FreeSql.Aop.AuditValueType.Insert)
            {
                if (e.Property.Name == "CreatTime")
                {
                    e.Value = DateTime.Now;
                }
                else if (e.Property.Name == "Creator")
                {
                    // 设置创建人为当前登录用户ID
                    if (DomainConfig.CurrentUserId != Guid.Empty)
                    {
                        e.Value = DomainConfig.CurrentUserId;
                    }
                }
                
            }
            else if (e.AuditValueType == FreeSql.Aop.AuditValueType.Update)
            {
                //// 防止更新实体时修改CreatTime和Creator字段
                //if (e.Property.Name == "CreatTime" || e.Property.Name == "Creator")
                //{
                //    // 忽略对这些字段的更新，不做任何修改
                //    return;
                //}
                
                if (e.Property.Name == "UpdateTime")
                {
                    e.Value = DateTime.Now;
                }
                else if (e.Property.Name == "Updater")
                {
                    // 设置更新人为当前登录用户ID
                    if (DomainConfig.CurrentUserId != Guid.Empty)
                    {
                        e.Value = DomainConfig.CurrentUserId;
                    }
                }
            }

        }

        private static void Aop_ConfigEntityProperty(object? sender, FreeSql.Aop.ConfigEntityPropertyEventArgs e)
        {
            if (e.Property.PropertyType == typeof(decimal) || e.Property.PropertyType == typeof(decimal?))
            {
                e.ModifyResult.Precision = 18;
                e.ModifyResult.Scale = 6;
            }
            else if (e.Property.PropertyType == typeof(float) || e.Property.PropertyType == typeof(float?))
            {
                e.ModifyResult.Precision = 18;
                e.ModifyResult.Scale = 2;
            }
        }
        
        private static void Aop_CurdAfter(object? sender, FreeSql.Aop.CurdAfterEventArgs e)
        {
            if (e.ElapsedMilliseconds > 2000)
            {
                DomainModuleEvents.LowerSqlAction?.Invoke(e.Sql);
            }
        }
    }
}

